package com.kgc.app.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kgc.app.mapper.EbookCategoryMapper;
import com.kgc.app.mapper.EbookEntryMapper;
import com.kgc.app.pojo.EbookCategory;
import com.kgc.app.pojo.EbookEntry;
import com.kgc.app.pojo.EbookEntryExample;
import com.kgc.app.service.EbookEntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 要求：
 *
 * @Date 2021/9/8
 */
@Service
public class EbookEntryServiceImpl implements EbookEntryService {

    @Autowired
    private EbookEntryMapper ebookEntryMapper;

    @Autowired
    private EbookCategoryMapper ebookCategoryMapper;

    public PageInfo<EbookEntry> selectBookByCondition(Integer categoryId, Integer pageNo, Integer pageSize) {
        EbookEntryExample entryExample = new EbookEntryExample();
        EbookEntryExample.Criteria criteria = entryExample.createCriteria();
        //条件拼接
        if (null != categoryId && categoryId!= 0){
            criteria.andCategoryIdEqualTo(categoryId);
        }
        //在查询之前要开启mybatis的分页
        PageHelper.startPage(pageNo,pageSize);
        List<EbookEntry> ebookEntries = ebookEntryMapper.selectByExample(entryExample);
        for (EbookEntry ebookEntry : ebookEntries) {
            EbookCategory ebookCategory = ebookCategoryMapper.selectByPrimaryKey(ebookEntry.getCategoryId());
            ebookEntry.setEbookCategory(ebookCategory);
        }
        PageInfo<EbookEntry> pageInfo = new PageInfo<EbookEntry>(ebookEntries);
        return pageInfo;
    }

    public int addBook(EbookEntry ebookEntry) {
        return ebookEntryMapper.insertSelective(ebookEntry);
    }

    public int delete(Integer id) {
        return ebookEntryMapper.deleteByPrimaryKey(id);
    }

    public int update(EbookEntry ebookEntry) {
        return ebookEntryMapper.updateByPrimaryKey(ebookEntry);
    }

    public EbookEntry selectBookById(Integer id) {
        EbookEntry ebookEntry = ebookEntryMapper.selectByPrimaryKey(id);
        EbookCategory ebookCategory = ebookCategoryMapper.selectByPrimaryKey(ebookEntry.getCategoryId());
        ebookEntry.setEbookCategory(ebookCategory);
        return ebookEntry;
    }
}
